package com.byl.common.utils.themeleaf;

import com.byl.sdk.utils.StringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.Context;
import org.thymeleaf.templateresolver.ClassLoaderTemplateResolver;

import java.io.*;

/**
 * Created by Administrator on 2019/12/5.
 */
@SuppressWarnings("ALL")
@Component
public class TemplateUtils {

    private final String SUFFIX=".html";

    private TemplateEngine templateEngine;

    /**
     * 生成静态文件
     * @param freeTempName 模板名称
     * @param context 数据内容
     * @param outFilePath 输出路径
     * @param fileName 生成的文件名 如果为null 用模板名称
     * @return
     */
    public boolean process(String freeTempName, Context context, String outFilePath,String fileName,String relPath) {
        BufferedWriter fileWriter = null;
        OutputStreamWriter osw=null;
        FileOutputStream fos=null;
        try {
            File file=new File(outFilePath);
            if(!file.exists())
                file.mkdirs();
            if(!StringUtil.isBlank(relPath))
                relPath=relPath+"/";
            file=new File(outFilePath,relPath+getFileName(fileName,freeTempName));
            fos=new FileOutputStream(file);
            osw=new OutputStreamWriter(fos,"UTF-8");
            fileWriter = new BufferedWriter(osw);
            getTemplateEngine().process(freeTempName, context,fileWriter);
        } catch (IOException e) {
            e.printStackTrace();
            return false;
        } finally {
            try {
                fos.close();
                osw.close();
                fileWriter.close();
            } catch (IOException e) {
                e.printStackTrace();
                return false;
            }
        }
        return true;
    }

    String getFileName(String fileName,String template){
        if(!StringUtil.isBlank(fileName))
             return fileName+SUFFIX;
        if(StringUtil.isBlank(template))
            return "";
        int pos=template.lastIndexOf("/");
        return template.substring(pos+1)+SUFFIX;
    }

    public TemplateEngine getTemplateEngine() {
        if(null==templateEngine){
            //创建模版加载器
            ClassLoaderTemplateResolver resolver = new ClassLoaderTemplateResolver();
            resolver.setPrefix("templates/");  //模板文件的所在目录
            resolver.setSuffix(".html");       //模板文件后缀
            resolver.setCharacterEncoding("UTF-8");
            //创建模板引擎
            templateEngine = new TemplateEngine();
            //将加载器放入模板引擎
            templateEngine.setTemplateResolver(resolver);
        }
        return templateEngine;
    }
}
